package com.yfker.pda;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.yfker.pda.model.InfusionBottleModel;
import com.yfker.pda.model.InfusionInfo;
import com.yfker.pda.utils.AESUtilHelp;
import com.yfker.pda.utils.TtsUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    public static final String KEY_ID = "2+DmyLnYl2WypAfMghaS8w==";
    public static final String SECRET = "l8hI1TJfjxiUWSPs";
    public static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
    private final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .callTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS).
            build();

    private Button mBtnAddBottle;

    private Button mBtnInit;

    private Button mBtnUnBind;

    private Button mBtnGetRobotCode;

    private RecyclerView mRecyclerView;

    private TextView mTvTips;

    private Button mBtnPauseInfusion;

    private Button mBtnStartInfusion;

    private InfusionBottleAdapter infusionBottleAdapter;

    private String robotCode;

    private ScanBroadcastReceiver scanBroadcastReceiver = null;

    private final String[] drugNames = new String[] {"葡萄糖", "氯化钠"};

    private final int[] drugCapacities = new int[] {200, 500};

    private int bottleNumber = 0;
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnAddBottle = findViewById(R.id.btn_add_bottle);
        mBtnGetRobotCode = findViewById(R.id.btn_get_robot_code);
        mBtnInit = findViewById(R.id.btn_init);
        mBtnUnBind = findViewById(R.id.btn_unbind);
        mRecyclerView = findViewById(R.id.recyclerView);
        mTvTips = findViewById(R.id.tv_tips);
        mBtnPauseInfusion = findViewById(R.id.btn_pause_infusion);
        mBtnStartInfusion = findViewById(R.id.btn_start_infusion);

        robotCode = SPStaticUtils.getString("robotCode", "");
        ToastUtils.getDefaultMaker().setGravity(Gravity.CENTER, 0, 0);

        infusionBottleAdapter = new InfusionBottleAdapter();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mRecyclerView.setAdapter(infusionBottleAdapter);

        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int px = SizeUtils.dp2px(16);
                int childAdapterPosition = parent.getChildAdapterPosition(view);
                if (childAdapterPosition > 0) {
                    outRect.left = px;
                }
            }
        });

        mBtnAddBottle.setOnClickListener(v -> {
            addBottle();
        });

        mBtnGetRobotCode.setOnClickListener(v -> {
            scan();
        });

        mBtnInit.setOnClickListener(v -> {
            ThreadUtils.executeBySingle(new ThreadUtils.SimpleTask<Object>() {
                @Override
                public Object doInBackground() throws Throwable {
                    boolean wifiAvailable = NetworkUtils.isWifiAvailable();
                    boolean g = NetworkUtils.is4G();
                    if (wifiAvailable || g) {
                        bind();
                    } else {
                        ToastUtils.showLong("网络未连接，请检查网络!");
                    }
                    return null;
                }

                @Override
                public void onSuccess(Object result) {

                }
            });
        });

        mBtnUnBind.setOnClickListener(v -> {
            TtsUtils.getInstance().speak("解绑设备成功");
            unbind();
        });

        mBtnPauseInfusion.setOnClickListener(v -> {
            pauseInfusion();
        });

        mBtnStartInfusion.setOnClickListener(v -> {
            startInfusion();
        });

//        updateInfusionInfo();

        TtsUtils.getInstance().init(this);
    }

    private void startInfusion() {
        if (TextUtils.isEmpty(robotCode)) {
            ToastUtils.showShort("请先获取设备码!");
            return;
        }

        // 时间戳加密
        long currentTimeMillis = System.currentTimeMillis();
        String encrypt = AESUtilHelp.Encrypt(String.valueOf(currentTimeMillis), SECRET);
        if (encrypt == null) {
            ToastUtils.showShort("获取加密参数错误!");
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("robotCode", robotCode);
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        Request request = new Request
                .Builder()
                .url("http://120.79.181.201:8168/begin")  // 开始输液
                .addHeader("keyId", KEY_ID)
                .addHeader("timeMillis", encrypt)
                .post(body)
                .build();
        okHttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        ToastUtils.showShort("开始输液");
                    }
                });

    }

    /**
     * 暂停输液
     */
    private void pauseInfusion() {
        if (TextUtils.isEmpty(robotCode)) {
            ToastUtils.showShort("请先获取设备码!");
            return;
        }

        // 时间戳加密
        long currentTimeMillis = System.currentTimeMillis();
        String encrypt = AESUtilHelp.Encrypt(String.valueOf(currentTimeMillis), SECRET);
        if (encrypt == null) {
            ToastUtils.showShort("获取加密参数错误!");
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("robotCode", robotCode);
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        Request request = new Request
                .Builder()
                .url("http://120.79.181.201:8168/pause")  // 暂停输液
                .addHeader("keyId", KEY_ID)
                .addHeader("timeMillis", encrypt)
                .post(body)
                .build();
        okHttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        ToastUtils.showShort("暂停输液完成");
                    }
                });
    }

    private void updateInfusionInfo() {
        if (TextUtils.isEmpty(robotCode)) {
            ToastUtils.showShort("请先获取设备码!");
            return;
        }

        // 时间戳加密
        long currentTimeMillis = System.currentTimeMillis();
        String encrypt = AESUtilHelp.Encrypt(String.valueOf(currentTimeMillis), SECRET);
        if (encrypt == null) {
            ToastUtils.showShort("获取加密参数错误!");
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("robotCode", robotCode);
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        Request request = new Request
                .Builder()
                .url("http://120.79.181.201:8168/infusion/robot/getInfoByRobotCode?robotCode=" + robotCode)  // 添加瓶子
                .addHeader("keyId", KEY_ID)
                .addHeader("timeMillis", encrypt)
//                .post(body)
                .get()
                .build();
        okHttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.e("Kevin", "没有正在输液的数据: " + e.getLocalizedMessage());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        Log.d("Kevin", "收到输液信息: " + response.body().string());
//                        if (response.isSuccessful()) {
//                            byte[] bytes = response.body().bytes();
//                            InfusionInfo infusionInfo = JSON.parseObject(bytes, InfusionInfo.class);
//                            Log.d("Kevin", "收到输液数据: " + infusionInfo.toString());
//                        }
                    }
                });
    }

    @SuppressLint("NotifyDataSetChanged")
    private void unbind() {
        mTvTips.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
        bottleNumber = 0;
        SPStaticUtils.put("robotCode", "");
        infusionBottleAdapter.clear();
        infusionBottleAdapter.notifyDataSetChanged();

        if (TextUtils.isEmpty(robotCode)) {
            ToastUtils.showShort("请先获取设备码!");
            return;
        }

        // 时间戳加密
        long currentTimeMillis = System.currentTimeMillis();
        String encrypt = AESUtilHelp.Encrypt(String.valueOf(currentTimeMillis), SECRET);
        if (encrypt == null) {
            ToastUtils.showShort("获取加密参数错误!");
            return;
        }

        showLoadingDialog();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("robotCode", robotCode);
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        Request request = new Request
                .Builder()
                .url("http://120.79.181.201:8168/infusion/equipment/unbind")  // 添加瓶子
                .addHeader("keyId", KEY_ID)
                .addHeader("timeMillis", encrypt)
                .post(body)
                .build();
        okHttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        ToastUtils.showShort("解绑设备失败!");
                        robotCode = "";
                        SPStaticUtils.put("robotCode", "");
                        hideLoading();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        hideLoading();
                        robotCode = "";
                        SPStaticUtils.put("robotCode", "");
                        if (response.isSuccessful()) {
                            ToastUtils.showShort("解绑设备成功!");
                        }
                    }
                });
    }

    private void scan() {
        if (TextUtils.isEmpty(robotCode)) {
            // 打开扫码获取二维码信息
            //app发送按键广播消息方式
            Log.d("Kevin", "发送扫码....");
            Intent intentBroadcast = new Intent();
            intentBroadcast.setAction("com.zkc.keycode");
            intentBroadcast.putExtra("keydown", 137);
            sendBroadcast(intentBroadcast);
        } else {
            ToastUtils.showLong("重复扫描");
            TtsUtils.getInstance().speak("重复扫码");
        }
    }

    private void addBottle() {
        if (TextUtils.isEmpty(robotCode)) {
            ToastUtils.showShort("请先获取设备码!");
            return;
        }

        // 时间戳加密
        long currentTimeMillis = System.currentTimeMillis();
        String encrypt = AESUtilHelp.Encrypt(String.valueOf(currentTimeMillis), SECRET);
        if (encrypt == null) {
            ToastUtils.showShort("获取加密参数错误!");
            return;
        }

        if (bottleNumber > drugCapacities.length - 1) {
            ToastUtils.showShort("配药数量已达上限");
            return;
        }

        showLoadingDialog();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("robotCode", robotCode);
        jsonObject.put("bottleNumber", bottleNumber + 1);
        jsonObject.put("capacity", drugCapacities[bottleNumber]);
        jsonObject.put("drugName", drugNames[bottleNumber]);
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        Request request = new Request
                .Builder()
                .url("http://120.79.181.201:8168/infusion/robot/add/bottle")  // 添加瓶子
                .addHeader("keyId", KEY_ID)
                .addHeader("timeMillis", encrypt)
                .post(body)
                .build();
        okHttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        ToastUtils.showShort("添加输液瓶失败");
                        hideLoading();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (response.isSuccessful()) {
                            bottleNumber++;
                            TtsUtils.getInstance().speak("上药完成");
                            hideLoading();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    notifyAddBottleUi(jsonObject);
                                }
                            });
                        }
                    }
                });
    }

    private void notifyAddBottleUi(JSONObject jsonObject) {
        Log.d("Kevin", "准备添加输液瓶...");
        mTvTips.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.VISIBLE);
        int bottleNumber = jsonObject.getIntValue("bottleNumber");
        int capacity = jsonObject.getIntValue("capacity");
        String robotCode = jsonObject.getString("robotCode");
        String drugName = jsonObject.getString("drugName");
        InfusionBottleModel infusionBottleModel = new InfusionBottleModel();
        infusionBottleModel.setBottleNumber(bottleNumber);
        infusionBottleModel.setCapacity(capacity);
        infusionBottleModel.setRobotCode(robotCode);
        infusionBottleModel.setDrugName(drugName);
        infusionBottleAdapter.addBottle(infusionBottleModel);
    }

    private void bind() {
        if (TextUtils.isEmpty(robotCode)) {
            ToastUtils.showShort("请先获取设备码!");
            TtsUtils.getInstance().speak("请先获取设备码");
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showLoadingDialog();
            }
        });

        // 时间戳加密
        long currentTimeMillis = System.currentTimeMillis();
        String encrypt = AESUtilHelp.Encrypt(String.valueOf(currentTimeMillis), SECRET);
        if (encrypt == null) {
            ToastUtils.showShort("获取加密参数错误!");
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("robotCode", robotCode);
        jsonObject.put("bindId", "32");
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        Request request = new Request
                .Builder()
                .url("http://120.79.181.201:8168/infusion/robot/bind/bed")  // 绑定病床
                .addHeader("keyId", KEY_ID)
                .addHeader("timeMillis", encrypt)
                .post(body)
                .build();
        okHttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        hideLoading();
                        ToastUtils.showShort("设备绑定失败");
                        Log.e("Kevin", "绑定病床失败: " + e.getLocalizedMessage());
                        TtsUtils.getInstance().speak("设备绑定失败");
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (response.isSuccessful()) {
                            bindPatient();
                        }
                    }
                });
    }

    private void bindPatient() {
        // 时间戳加密
        long currentTimeMillis = System.currentTimeMillis();
        String encrypt = AESUtilHelp.Encrypt(String.valueOf(currentTimeMillis), SECRET);
        if (encrypt == null) {
            ToastUtils.showShort("获取加密参数错误!");
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("robotCode", robotCode);
        jsonObject.put("userName", "林妙妙");
        jsonObject.put("age", 28);
        jsonObject.put("doctorInCharge", "张林栋");
        jsonObject.put("gender", "0");
        jsonObject.put("nurse", "李小丽");
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        Request request = new Request
                .Builder()
                .url("http://120.79.181.201:8168/infusion/robot/bind/patient")  // 绑定病床
                .addHeader("keyId", KEY_ID)
                .addHeader("timeMillis", encrypt)
                .post(body)
                .build();
        okHttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        hideLoading();
                        ToastUtils.showShort("设备绑定失败");
                        TtsUtils.getInstance().speak("设备绑定失败");
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (response.isSuccessful()) {
                            hideLoading();
                            TtsUtils.getInstance().speak("设备绑定成功,请开始上药");
                            SPStaticUtils.put("robotCode", robotCode);
                            ToastUtils.showShort("设备绑定成功");
                        }
                    }
                });
    }

    private void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }

        if (!loadingDialog.isShowing())
            loadingDialog.show();
    }

    private void hideLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onResume() {
        super.onResume();
        //1.8.11以前版本使用 intentFilter.addAction("com.zkc.scancode");
        if(scanBroadcastReceiver==null) {
            scanBroadcastReceiver = new ScanBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.scancode.resault");
            registerReceiver(scanBroadcastReceiver, intentFilter);
        }
    }

    @Override
    protected void onDestroy() {
        if (scanBroadcastReceiver != null) {
            unregisterReceiver(scanBroadcastReceiver);
        }
        TtsUtils.getInstance().release();
        super.onDestroy();
    }

    public final class ScanBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getExtras().getString("code");
            Log.d("Kevin", "code: " + code);
            MainActivity.this.robotCode = code;
            TtsUtils.getInstance().speak("扫码成功");
        }
    }
}